package net.wangds.yunz.auth.filter;

import net.wangds.log.helper.LogHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class AnonymousFilter extends AnonymousAuthenticationFilter {
    public AnonymousFilter(String key) {
        super(key);
    }

    public AnonymousFilter(String key, Object principal, List<GrantedAuthority> authorities) {
        super(key, principal, authorities);
    }

    @Override
    protected Authentication createAuthentication(HttpServletRequest request) {

        String uri = request.getRequestURI();
        if(!StringUtils.contains(uri, "/file/")) {
            LogHelper.debug(() -> "创建匿名用户身份认证信息，" + request.getRequestURI());
        }
        //List<GrantedAuthority> authorities = this.getAuthorities();
        //authorities.add(new SimpleGrantedAuthority("ROLE_ANONYMOUS"));
        Authentication auth = new AnonymousAuthenticationToken(
                "ANONYMOUS",
                this.getPrincipal(),
                this.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);
        return auth;
    }

}
